<template>
  <!-- 资产点检工单表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="900px"
      draggable
      @close="closeDialog"
      :append-to-body="true"
    >
      <h4 class="mb-[20px]">检验记录</h4>
      <div class="formTable" style="margin-top: 20px">
        <el-table
          :data="consumeInspectList"
          style="width: 100%"
          :key="Math.random"
          max-height="25vh"
          :header-cell-style="{ textAlign: 'center' }"
          border
        >
          <el-table-column
            label="序号"
            type="index"
            min-width="100"
            align="center"
          />

          <el-table-column
            label="检验单号"
            props="inspectOrderNo"
            min-width="150"
            align="left"
          >
            <template #default="{ $index, row }">
              <span
                style="
                  text-decoration: underline;
                  cursor: pointer;
                  color: #509ee7;
                "
                @click="openDialogdetail(row)"
                >{{ row.inspectOrderNo }}11</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="检验时间"
            props="checkTime"
            min-width="150"
            align="left"
          >
            <template #default="{ $index, row }">
              {{ row.checkTime }}
            </template>
          </el-table-column>
          <el-table-column
            label="检验项目名称"
            props="sopItemResult"
            min-width="150"
            align="center"
          >
            <template #default="{ $index, row }">
              {{ row.sopItemResult ? "正常" : "异常" }}
            </template>
          </el-table-column>
          <el-table-column
            label="检验结果"
            props="sopItemValue"
            min-width="180"
            align="center"
          >
            <template #default="{ $index, row }">
              {{ row.sopItemValue }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <h4 class="mb-[20px]">使用寿命</h4>
      <div class="formTable" style="margin-top: 20px">
        <el-table
          :data="consumeLifeList"
          style="width: 100%"
          :key="Math.random"
          max-height="25vh"
          :header-cell-style="{ textAlign: 'center' }"
          border
        >
          <el-table-column
            label="序号"
            type="index"
            min-width="100"
            align="center"
          />

          <el-table-column
            label="使用寿命"
            props="useLife"
            min-width="right"
            align="left"
          >
            <template #default="{ $index, row }">
              {{ row.useLife }}
            </template>
          </el-table-column>
          <el-table-column
            label="上架时间"
            props="installTime"
            min-width="180"
            align="center"
          >
            <template #default="{ $index, row }">
              {{ row.installTime }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <toolingMoldEdit-Mater
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <toolingMoldEdit-Mater
      :visible="addDialog1.visible"
      :title="addDialog1.title"
      :data="addDialog1.data"
      :is-readonly="addDialog1.readvisible"
      @change-visible="changeVisible1"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
import { textAlign } from "html2canvas/dist/types/css/property-descriptors/text-align";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQMSPOINTCHECKORDERADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  assetKind: "",
  planNo: "",
  planName: "",
  orderNo: "",
  workTime: "",
  sopTypeId: "",
  sopTypeName: "",
  sopTypeCode: "",
  sopStandardId: "",
  sopStandardCode: "",
  sopStandardName: "",
  assetId: "",
  assetCode: "",
  assetName: "",
  orderStatus: "",
  remarks: "",
  executePersonId: "",
  executePersonName: "",
  checkPersonId: "",
  checkPersonName: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  details: [
    {
      id: "",
      version: "",
      orderId: "",
      seq: "",
      sopItemId: "",
      sopItemName: "",
      sopItemValue: "",
      sopItemResult: "",
      sopItemStandard: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      sopItemValueId: "",
      sopStandardId: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  assetKind: [],
  orderNo: [],
  workTime: [],
  sopTypeId: [],
  sopTypeCode: [],
  sopStandardId: [],
  sopStandardCode: [],
  assetId: [],
  assetCode: [],
  assetName: [],
  orderStatus: [],
  remarks: [],
  executePersonId: [],
  executePersonName: [],
  checkPersonId: [],
  checkPersonName: [],
  deleted: [],
  createTime: [],
  createdUserId: [],
  createdUserName: [],
  lastUpdateTime: [],
  lastUpdatedUserId: [],
  lastUpdatedUserName: [],
  sonsopItemName: [],
  sonsopItemValue: [],
  sonsopItemResult: [],
  sonsopItemStandard: [],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  version: "",
  orderId: "",
  seq: "",
  sopItemId: "",
  sopItemName: "",
  sopItemValue: "",
  sopItemResult: "",
  sopItemStandard: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  sopItemValueId: "",
  sopStandardId: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  async (newVal: any) => {
    if (newVal?.id) {
      await getConsumeInspectList(newVal?.id);
      await getConsumeLifeList(newVal?.id);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  // resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.version = "";
  formData.assetKind = "";
  formData.orderNo = "";
  formData.planNo = "";
  formData.planName = "";
  formData.workTime = "";
  formData.sopTypeId = "";
  formData.sopTypeName = "";
  formData.sopTypeCode = "";
  formData.sopStandardId = "";
  formData.sopStandardCode = "";
  formData.sopStandardName = "";
  formData.assetId = "";
  formData.assetCode = "";
  formData.assetName = "";
  formData.orderStatus = "";
  formData.remarks = "";
  formData.executePersonId = "";
  formData.executePersonName = "";
  formData.checkPersonId = "";
  formData.checkPersonName = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

const uploadApi = import.meta.env.VITE_APP_BASE_API;
// 预览url前缀
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;

const handlePictureCardPreview = (url: string) => {
  url = url?.replace("fileCenter/download/", "fileCenter/preview/");
  window.open(url);
};

/** 资产点检工单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/qms/qmspointcheckorder/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/qms/qmspointcheckorder/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

const addDialog = reactive({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  docType: "1",
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamCommonDoc/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开资产型号表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  console.log(roleObj);

  addDialog.title = "原材料详情";
  // getInfo(roleObj.id);
  addDialog.data = roleObj;
  addDialog.visible = true;
  addDialog.readvisible = true;
}

function changeVisible(value: boolean, docType: string) {
  addDialog.visible = value;
  addDialog.data = {};
}

const addDialog1 = reactive({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  docType: "1",
});

// 查询详情
async function getInfo1(id: string) {
  request({
    url: `/eam/eamCommonDoc/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog1.data = data.data;
      addDialog1.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开资产型号表单弹窗 详情 */
function openDialogdetail1(roleObj?: any) {
  console.log(roleObj);

  addDialog1.title = "原材料详情";
  // getInfo(roleObj.id);
  addDialog1.visible = true;
  addDialog1.readvisible = true;
}

function changeVisible1(value: boolean, docType: string) {
  addDialog1.visible = value;
  addDialog1.data = {};
}

// 获取检验记录列表
const consumeInspectList = ref([]);
async function getConsumeInspectList(id: string) {
  await request({
    url: `/qms/directionTrace/getConsumeInspectList`,
    method: "post",
    data: {
      consumeId: id,
    },
  }).then((data) => {
    consumeInspectList.value = data.data;
    console.log(consumeInspectList.value);
  });
}
// // 获取维修记录列表
// const maintenanceRecordList = ref([]);
// async function getMaintenanceRecordList(id: string) {
//   await request({
//     url: `/qms/directionTrace/getMouldMaintainList`,
//     method: "post",
//     data: {
//       rawMouldId: id,
//     },
//   }).then((data) => {
//     maintenanceRecordList.value = data.data;
//     console.log(maintenanceRecordList.value);
//   });
// }
// 使用寿命列表
const consumeLifeList = ref([]);
async function getConsumeLifeList(id: string) {
  await request({
    url: `/qms/directionTrace/getConsumeLifeList`,
    method: "post",
    data: {
      consumeId: id,
    },
  }).then((data) => {
    consumeLifeList.value = data.data;
    console.log(consumeLifeList.value);
  });
}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}

:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}

:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}

:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  min-width: 115px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 170px;
}
</style>
